package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"logi-whse/cache"
	"logi-whse/model"
	"strconv"
	"time"
)

func RepoOrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	/*
		SELECT
		repo_orders.id,
		repos.repo_name,
		repos.repo_num,
		repos.repo_code,
		repo_orders.order_adder,
		repo_orders.order_num
		FROM
		repo_orders
		LEFT JOIN repos ON repo_orders.id=repos.id
	*/
	var data []model.RepoOrderList
	redis_key := "list_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("repo_orders").
			Joins("LEFT JOIN repos ON repo_orders.id=repos.id").
			Select(
				"repo_orders.id",
				"repos.repo_name",
				"repos.repo_num",
				"repos.repo_code",
				"repo_orders.order_adder",
				"repo_orders.order_num").
			Offset(offset).Limit(size).Find(&data)
		jsonData, _ := json.Marshal(&data)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &data)
	}
	var total int64
	model.DB.Table("repo_orders").
		Joins("LEFT JOIN repos ON repo_orders.id=repos.id").
		Select(
			"repo_orders.id",
			"repos.repo_name",
			"repos.repo_num",
			"repos.repo_code",
			"repo_orders.order_adder",
			"repo_orders.order_num").Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  data,
		"total": total,
	})
	return
}
